package com.swak.persistence.mybatis.methods.impls;

import java.util.List;

import com.swak.define.ColumnDefine;
import com.swak.persistence.mybatis.methods.AbstractMethod;
import com.swak.persistence.mybatis.methods.Sqls;
import com.swak.utils.StringUtils;

/**
 * 插入
 * 
 * @author lifeng
 * @date 2021年1月22日 上午9:10:32
 */
public class BatchInsert extends AbstractMethod {

	@Override
	protected void doInject() {
		if (!this.supportMethod(Sqls.BATCH_INSERT)) {
			return;
		}
		String sql = new StringBuilder().append(SCRIPT_START).append(INSERT).append(SPACE).append(this.table.getName())
				.append(LEFT_BRACKET).append(this.parseSqlColumns()).append(RIGHT_BRACKET).append(SPACE).append(VALUES)
				.append("<foreach collection=\"list\" item=\"item\" index=\"index\" separator=\",\" >")
				.append(LEFT_BRACKET).append(this.parseInsertSqlPropertyWithPrex("item")).append(RIGHT_BRACKET)
				.append("</foreach>").append(SCRIPT_END).toString();

		this.addInsertMappedStatement(List.class, Sqls.BATCH_INSERT.getMethod(), sql);
	}

	/**
	 * insert 后面的属性值
	 * 
	 * @param <T>
	 * @param table
	 * @return
	 */
	protected String parseInsertSqlPropertyWithPrex(String prex) {
		StringBuilder sql = new StringBuilder();
		for (ColumnDefine column : table.columns) {
			String name = column.javaProperty;
			sql.append(HASH_LEFT_BRACE).append(StringUtils.isNotBlank(prex) ? prex + DOT : StringUtils.EMPTY)
					.append(name).append(RIGHT_BRACE).append(SPLIT);
		}
		if (table.hasColumn()) {
			sql.delete(sql.lastIndexOf(SPLIT), sql.length() - 1);
		}
		return sql.toString();
	}
}